
package me.zhengjie.service.impl;

import me.zhengjie.base.AjaxResult;
import me.zhengjie.domain.AppDaka;
import me.zhengjie.modules.system.service.RoleService;
import me.zhengjie.modules.system.service.UserService;
import me.zhengjie.modules.system.service.dto.RoleSmallDto;
import me.zhengjie.modules.system.service.dto.UserDto;
import me.zhengjie.modules.system.service.dto.UserQueryCriteria;
import me.zhengjie.rest.vo.Gps2VO;
import me.zhengjie.service.AppDakaConfigService;
import me.zhengjie.service.dto.AppDakaConfigDto;
import me.zhengjie.utils.*;
import lombok.RequiredArgsConstructor;
import me.zhengjie.repository.AppDakaRepository;
import me.zhengjie.service.AppDakaService;
import me.zhengjie.service.dto.AppDakaDto;
import me.zhengjie.service.dto.AppDakaQueryCriteria;
import me.zhengjie.service.mapstruct.AppDakaMapper;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.sql.Timestamp;
import java.util.*;
import java.io.IOException;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author IQW
* @date 2022-07-18
**/
@Service
@RequiredArgsConstructor
public class AppDakaServiceImpl implements AppDakaService {

    private final AppDakaRepository appDakaRepository;
    private final AppDakaMapper appDakaMapper;
    private final UserService userService;
    private final RoleService roleService;
    private final AppDakaConfigService appDakaConfigService;


    @Override
    public Map<String,Object> queryAllApi(AppDakaQueryCriteria criteria, Pageable pageable){

        //不做分页
        if(pageable.getPageNumber()>0){
            return AjaxResult.success();
        }
        //直接查询1个月的数据，不做分页
        criteria.setUserId(SecurityUtils.getCurrentUserId().intValue());
        Sort sort = Sort.by(Sort.Direction.ASC,"dkId");
        List<AppDaka> list = appDakaRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),sort);

        List<Map> listRet = new LinkedList<>();
        List<Map> list2 = new ArrayList<>();
        String dayStr = "";
        int i = 0;
        for (AppDaka item :list){
            i++;
            String tmp = DateUtils.TimestampToStrDay(item.getCreateTime());
            if(dayStr.equals("") || item.getFlag() == 1){
                dayStr = tmp;
            }
            if(dayStr.equals(tmp)){
                Map mtmp = new HashMap();
                mtmp.put("title",item.getTitle()+" "+item.getStime());
                mtmp.put("dktime", item.getStatus() == 0 ?"未打卡":DateUtils.TimestampToStrHM(item.getCreateTime())+"已打卡");
                mtmp.put("status",item.getStatus());
                list2.add(mtmp);

                if(item.getFlag() == 4 || i>=list.size()) {
                    Map imap = new HashMap();
                    imap.put("title", dayStr);
                    imap.put("json", list2);
                    listRet.add(imap);
                    //重置
                    list2 = new ArrayList<>();
                }
            }
        }
        return AjaxResult.success(listRet);
    }

    @Override
    public Map<String,Object> queryAll(AppDakaQueryCriteria criteria, Pageable pageable){

        //获取最小权限
        Integer currentLevel =  Collections.min(roleService.findByUsersId(SecurityUtils.getCurrentUserId()).stream().map(RoleSmallDto::getLevel).collect(Collectors.toList()));
        System.out.println("min level:"+currentLevel);
        if(currentLevel<=2){
            //管理员查看所有
        }else{
            //查看当前责任区
            Long userId = SecurityUtils.getCurrentUserId();
            UserDto user = userService.findById(userId);
            criteria.setAreaId(user.getAreaId());
        }

        Page<AppDaka> page = appDakaRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);

        Page<AppDakaDto> page2 = page.map(appDakaMapper::toDto);
        //查询用户信息
        page2.getContent().forEach(AppDakaDto -> {
            UserDto user = userService.findById(AppDakaDto.getUserId());
            if(null!=user){
                AppDakaDto.setNickName(user.getNickName());
                AppDakaDto.setUsername(user.getUsername());
                AppDakaDto.setPhone(user.getPhone());
            }
        });
        return PageUtil.toPage(page2);
    }

    @Override
    public List<AppDakaDto> queryAll(AppDakaQueryCriteria criteria){
        return appDakaMapper.toDto(appDakaRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    public List<AppDakaDto> queryAllAsc(AppDakaQueryCriteria criteria){
        Sort sort = Sort.by(Sort.Direction.ASC,"dkId");
        return appDakaMapper.toDto(appDakaRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),sort));
    }

    @Override
    public void lastDayDaka() {


        //先默认读取一条打卡配置 TODO
        AppDakaConfigDto dakaConfigDto = appDakaConfigService.findById(1);
        if(null == dakaConfigDto){
            System.out.println("暂未配置打卡规则");
        }
        //查询用户
        UserQueryCriteria criteriaUser = new UserQueryCriteria();
        criteriaUser.setType(2);
        criteriaUser.setEnabled(true);
        List<UserDto> userDtos = userService.queryAll(criteriaUser);
        for (UserDto userDto :userDtos){
            //查询用户昨天所有打卡数据
            AppDakaQueryCriteria criteria = new AppDakaQueryCriteria();
            criteria.setUserId(userDto.getId().intValue());
            List<Timestamp> wlist = new LinkedList<>();
            wlist.add(DateUtils.getYesterDayStartTimestamp());
            wlist.add(DateUtils.getYesterDayEndTimestamp());
            criteria.setCreateTime(wlist);
            List<AppDakaDto> list = this.queryAllAsc(criteria);
            int dakaFlag = 1;
            if(list.size()>0){
                dakaFlag = list.get(list.size()-1).getFlag()+1;
            }
            if(dakaFlag >= 4){
                continue;   //跳过
            }

            //执行打卡-根据当前时间自动插入缺卡（信息）
            for (;dakaFlag <= 4;dakaFlag++) {

                String title = "上班";
                String stime = "";

                if (dakaFlag == 1) {
                    stime = StringUtils.timeCutSec(dakaConfigDto.getTime1());

                } else if (dakaFlag == 2) {
                    stime = StringUtils.timeCutSec(dakaConfigDto.getTime2());
                    title = "下班";
                } else if (dakaFlag == 3) {
                    stime = StringUtils.timeCutSec(dakaConfigDto.getTime3());

                } else if (dakaFlag == 4) {
                    stime = StringUtils.timeCutSec(dakaConfigDto.getTime4());
                    title = "下班";
                }

                AppDaka appDaka = new AppDaka();
                appDaka.setUserId(userDto.getId().intValue());
                appDaka.setAreaId(userDto.getAreaId());
                appDaka.setTitle(title);
                appDaka.setStime(stime);
                appDaka.setFlag(dakaFlag);
                appDaka.setNum(dakaConfigDto.getNum());
                //插入昨天日期
                appDaka.setCreateTime(DateUtils.getYesterDayStartTimestamp());

                appDaka.setStatus(0);   //缺卡
                appDakaRepository.save(appDaka);

                if(dakaConfigDto.getNum() == 2){
                    if(dakaFlag == 1){
                        dakaFlag = 3;   //只有2步（1，4）
                    }
                }
            }

        }
    }

    @Override
    @Transactional
    public AppDakaDto findById(Integer dkId) {
        AppDaka appDaka = appDakaRepository.findById(dkId).orElseGet(AppDaka::new);
        ValidationUtil.isNull(appDaka.getDkId(),"AppDaka","dkId",dkId);
        return appDakaMapper.toDto(appDaka);
    }

    @Override
    public Map info() {

        Integer userId = SecurityUtils.getCurrentUserId().intValue();
        UserDto user = userService.findById(userId);
        if(null == user.getAreaId()){
            return AjaxResult.error("用户未设置责任区");
        }

        //先默认读取一条打卡配置
        AppDakaConfigDto dakaConfigDto = appDakaConfigService.findById(user.getAreaId());
        if(null == dakaConfigDto){
            return AjaxResult.error("所在责任区，暂未配置规则");
        }

        //查询用户今天打卡记录（2或4条）
        AppDakaQueryCriteria criteria = new AppDakaQueryCriteria();
        criteria.setUserId(userId);
        List<Timestamp> wlist = new LinkedList<>();
        wlist.add(DateUtils.getDayStartTimestamp());
        wlist.add(DateUtils.getDayEndTimestamp());
        criteria.setCreateTime(wlist);
        List<AppDakaDto> list = this.queryAllAsc(criteria);

        String left1,right1;
        String tip = "";
        int status = 1;
        int lastDaka = 0; //最后一次打卡档位
        Long dktime = 0L;    //下一个下班打卡时间戳

        if(list.size()>0){
            lastDaka = list.get(list.size()-1).getFlag();
        }

        String left2="",right2="";
        Integer status1=0,status2=0;

        int[] nowTime3 = DateUtils.getTimeSplitAll();
        if(dakaConfigDto.getNum() == 2){
            int[] config1 = StringUtils.getSFMByStr(dakaConfigDto.getTime1());
            int[] config4 = StringUtils.getSFMByStr(dakaConfigDto.getTime4());
            left1 = "上班"+ StringUtils.timeCutSec(dakaConfigDto.getTime1());
            right1 = "下班"+StringUtils.timeCutSec(dakaConfigDto.getTime4());

            if(nowTime3[3]<config1[3]){
                tip = "上班打卡";
            }else if(nowTime3[3]<config4[3]){
                tip = "下班打卡";
            }else{
                tip = "休息中";
                status = 0;
            }

            String[] arr1 = getDkData(list,1);
            left2 = arr1[0];
            status1 = Integer.parseInt(arr1[1]);

            String[] arr4 = getDkData(list,4);
            right2 = arr4[0];
            status2 = Integer.parseInt(arr4[1]);

            if(lastDaka == 1) {
                //必须上一个状态打卡过，才检测当前状态早退
                dktime = DateUtils.strToLong((DateUtils.getDate() + " " + dakaConfigDto.getTime4().trim()));
            }

        }else{

            int[] config1 = StringUtils.getSFMByStr(dakaConfigDto.getTime1());
            int[] config2 = StringUtils.getSFMByStr(dakaConfigDto.getTime2());
            int[] config3 = StringUtils.getSFMByStr(dakaConfigDto.getTime3());
            int[] config4 = StringUtils.getSFMByStr(dakaConfigDto.getTime4());

            if( nowTime3[3] <= config2[3] ){
                left1 = "上班"+ StringUtils.timeCutSec(dakaConfigDto.getTime1());
                right1 = "下班"+StringUtils.timeCutSec(dakaConfigDto.getTime2());

                if(lastDaka == 1 || lastDaka == 3) {
                    //必须上一个状态打卡过，才检测当前状态早退
                    dktime = DateUtils.strToLong((DateUtils.getDate() + " " + dakaConfigDto.getTime2().trim()));
                }
                String[] arr1 = getDkData(list,1);
                left2 = arr1[0];
                status1 = Integer.parseInt(arr1[1]);

                String[] arr2 = getDkData(list,2);
                right2 = arr2[0];
                status2 = Integer.parseInt(arr2[1]);

            }else {

                left1 = "上班"+ StringUtils.timeCutSec(dakaConfigDto.getTime3());
                right1 = "下班"+StringUtils.timeCutSec(dakaConfigDto.getTime4());

                if(lastDaka == 3) {
                    //必须上一个状态打卡过，才检测当前状态早退
                    dktime = DateUtils.strToLong((DateUtils.getDate() + " " + dakaConfigDto.getTime4().trim()));
                }

                String[] arr3 = getDkData(list,3);
                left2 = arr3[0];
                status1 = Integer.parseInt(arr3[1]);

                String[] arr4 = getDkData(list,4);
                right2 = arr4[0];
                status2 = Integer.parseInt(arr4[1]);

            }

            //这里需要真实数据来查询 TODO
            if(list.size() == 0) {
                tip = "上班打卡";
            }else {
                Integer lastFlag = list.get(list.size() - 1).getFlag();
                if(lastFlag == 4){
                    tip = "休息中";
                    status = 0;
                }else{
                    if (nowTime3[3] < config1[3]) {
                        tip = "上班打卡";

                    } else if (nowTime3[3] < config2[3]) {
                        tip = "下班打卡";

                    } else if (nowTime3[3] < config3[3]) {
                        tip = "上班打卡";

                    } else if (nowTime3[3] < config4[3]) {
                        tip = "下班打卡";

                    }
                }
            }

        }

        //加强检测
        if(list.size() >= dakaConfigDto.getNum()){
            tip = "休息中";
            status = 0;
        }


        String zhaohu1 = DateUtils.getDate();
        if(nowTime3[0]<=12){
            zhaohu1 += "上午班打卡";
        }else{
            zhaohu1 += "下午班打卡";
        }

        Map ret = new HashMap();
        ret.put("zhaohu1",zhaohu1);
        ret.put("zhaohu2", DateUtils.getHello());
        ret.put("nickName",user.getNickName());
        ret.put("roleName","巡护员");
        ret.put("workNo",user.getWorkNo());
        ret.put("avatarPath",StringUtils.getUserHead(user.getAvatarPath()));

        ret.put("left1",left1);
        ret.put("left2",left2);
        ret.put("left3",status1);
        ret.put("right1",right1);
        ret.put("right2",right2);
        ret.put("right3",status2);
        ret.put("tip",tip);
        ret.put("dktime",dktime);
        ret.put("status",status);

        return AjaxResult.success(ret);
    }

    //检索用户打卡信息
    private String[] getDkData(List<AppDakaDto> list,int flag){

        if(list.size() == 0){
            return new String[]{"", "0"};
        }
        for (AppDakaDto item : list){
            if(flag == item.getFlag()){
                String s1 = item.getTitle()+" "+ DateUtils.getTime3(item.getCreateTime().getTime());
                String s2 = item.getStatus().toString();
                return new String[]{s1,s2};
            }
        }
        return new String[]{"", "0"};
    }


    @Override
    public Map dakaAct(Gps2VO gpsVO) {

        if(StringUtils.isNull(gpsVO.getLon())||StringUtils.isNull(gpsVO.getLat())){
            return AjaxResult.error("GPS参数错误");
        }

        UserDto userDto = userService.findById(SecurityUtils.getCurrentUserId());

        Integer userId = userDto.getId().intValue();

        //先默认读取一条打卡配置
        AppDakaConfigDto dakaConfigDto = appDakaConfigService.findById(userDto.getAreaId());
        if(null == dakaConfigDto){
            return AjaxResult.error("暂未配置打卡规则");
        }
        System.out.println("--------上送经纬度xcx-------");
        System.out.println(gpsVO.getLon());
        System.out.println(gpsVO.getLat());
        System.out.println(gpsVO.getWifi());
        int checkOk = 0; //范围 和 wifi名称不能同时为空
        int checkNum = 0; //检测项

        //检测打卡范围
        if(!StringUtils.isEmpty(dakaConfigDto.getLat()) && !StringUtils.isEmpty(dakaConfigDto.getLon())){

            Integer mails = dakaConfigDto.getFanwei();
            //小程序传的wgps坐标,需要转换为gcj02坐标
            Gps gpsChange = GPSMath.wgs84_To_Gcj02(gpsVO.getLat(),gpsVO.getLon());
            double gpsMails = GPSMath.getMeter(gpsChange.toDouble(),new double[]{dakaConfigDto.getLon(),dakaConfigDto.getLat()} );

            System.out.println("转换后："+gpsChange.toString());
            System.out.println("计算距离："+gpsMails+"，目标距离："+mails);

            if(gpsMails > mails){
//                return AjaxResult.error("抱歉，不在打卡范围");
            }else{
                checkOk++;
            }
        }else{
            checkNum++;
        }

        //检测WIFI名称（是否包含）
        if(!StringUtils.isEmpty(dakaConfigDto.getWifi())){

            System.out.println("WIFI："+gpsVO.getWifi());

            if(StringUtils.isEmpty(gpsVO.getWifi()) || !StringUtils.checkContains(dakaConfigDto.getWifi(),gpsVO.getWifi()) ){
//                return AjaxResult.error("抱歉，请在指定WIFI环境打卡");
            }else{
                checkOk++;
            }
        }else{
            checkNum++;
        }
        //2者只检测之一
        if(checkNum == 2){
            return AjaxResult.error("请联系管理员配置打卡规则");
        }
        if(checkOk < 1){
            return AjaxResult.error("请在办公区域或指定WIFI环境下打卡");
        }

        //查询用户今天打卡记录（2或4条）
        AppDakaQueryCriteria criteria = new AppDakaQueryCriteria();
        criteria.setUserId(userId);
        List<Timestamp> wlist = new LinkedList<>();
        wlist.add(DateUtils.getDayStartTimestamp());
        wlist.add(DateUtils.getDayEndTimestamp());
        criteria.setCreateTime(wlist);
        List<AppDakaDto> list = this.queryAllAsc(criteria);
        if(list.size()>=dakaConfigDto.getNum()){
            return AjaxResult.error("抱歉，今天已经下班");
        }
        int dakaedFlag = 0;
        if(list.size()>0){
            //取出最后一条记录
            dakaedFlag = list.get(list.size()-1).getFlag();
        }

        int dakaFlag = 0;   //查询目前应该打卡的档位（1，2，3，4）
        int dkstatus = 1;   //当前打卡状态
        String stime = "";

        int dakaRealByTime = 0; //根据当前时间，实际应该打卡档位

        int[] nowTime3 = DateUtils.getTimeSplitAll();

        int[] config1 = StringUtils.getSFMByStr(dakaConfigDto.getTime1());
        int[] config2 = StringUtils.getSFMByStr(dakaConfigDto.getTime2());
        int[] config3 = StringUtils.getSFMByStr(dakaConfigDto.getTime3());
        int[] config4 = StringUtils.getSFMByStr(dakaConfigDto.getTime4());

        if(dakaConfigDto.getNum() == 2){

            //找出他现在应该打卡哪个档位
            if(dakaedFlag == 4){
                return AjaxResult.error("抱歉，今天已经下班");
            }else if(dakaedFlag == 0){
                dakaFlag = 1;
            }else if(dakaedFlag == 1){
                dakaFlag = 4;
            }

            //根据当前应打卡档位，再根据当前时间判断打卡状态（1正常，2早退，3迟到）（0缺卡暂不考虑）
            if(dakaFlag == 0){
                return AjaxResult.error("打卡状态异常");
            }

            //根据时间判断
            if(dakaFlag <=1 ) {
                if (nowTime3[3] < config1[3]) {
                    dakaRealByTime = 1;

                }else {
                    dakaRealByTime = 4;
                }
            }else{
                dakaRealByTime = 4;
            }

        }else{

            //找出他现在应该打卡哪个档位
            if(dakaedFlag == 4){
                return AjaxResult.error("抱歉，今天已经下班");
            }else if(dakaedFlag == 0){
                dakaFlag = 1;
            }else if(dakaedFlag == 1){
                dakaFlag = 2;
            }else if(dakaedFlag == 2){
                dakaFlag = 3;
            }else if(dakaedFlag == 3){
                dakaFlag = 4;
            }

            //根据当前应打卡档位，再根据当前时间判断打卡状态（1正常，2早退，3迟到）（0缺卡暂不考虑）
            if(dakaFlag == 0){
                return AjaxResult.error("打卡状态异常");
            }

            //根据时间判断
            if(dakaFlag <= 1) {
                if (nowTime3[3] < config1[3]) {
                    dakaRealByTime = 1;

                } else if (nowTime3[3] < config2[3]) {
                    dakaRealByTime = 2;

                } else if (nowTime3[3] < config3[3]) {
                    dakaRealByTime = 3;

                } else {
                    dakaRealByTime = 4;
                }
            }else if(dakaFlag == 2){
                if (nowTime3[3] < config2[3]) {
                    dakaRealByTime = 2;

                } else if (nowTime3[3] < config3[3]) {
                    dakaRealByTime = 3;

                } else {
                    dakaRealByTime = 4;
                }
            }else if(dakaFlag == 3){
                if (nowTime3[3] < config3[3]) {
                    dakaRealByTime = 3;

                } else {
                    dakaRealByTime = 4;
                }
            }else{
                dakaRealByTime = 4;
            }
        }

        //执行打卡-根据当前时间自动插入缺卡（信息）
        for (;dakaFlag<= dakaRealByTime;dakaFlag++) {

            String title = "上班";

            if (dakaFlag == 1) {
                stime = StringUtils.timeCutSec(dakaConfigDto.getTime1());

            } else if (dakaFlag == 2) {
                stime = StringUtils.timeCutSec(dakaConfigDto.getTime2());
                title = "下班";
            } else if (dakaFlag == 3) {
                stime = StringUtils.timeCutSec(dakaConfigDto.getTime3());

            } else if (dakaFlag == 4) {
                stime = StringUtils.timeCutSec(dakaConfigDto.getTime4());
                title = "下班";
            }

            AppDaka appDaka = new AppDaka();
            appDaka.setUserId(userId);
            appDaka.setAreaId(userDto.getAreaId());
            appDaka.setTitle(title);
            appDaka.setStime(stime);
            appDaka.setFlag(dakaFlag);
            appDaka.setNum(dakaConfigDto.getNum());
            appDaka.setCreateTime(DateUtils.getNowTimestamp());

            if(dakaRealByTime == dakaFlag){


                //判断状态
                if(dakaFlag == 1){
                    if(nowTime3[3]>config1[3]){
                        dkstatus = 3;
                    }
                }else if(dakaFlag == 2){
                    if(nowTime3[3]<config2[3]){
                        dkstatus = 2;
                    }
                }else if(dakaFlag == 3){
                    if(nowTime3[3]>config3[3]){
                        dkstatus = 3;
                    }
                }else if(dakaFlag == 4){
                    if(nowTime3[3]<config4[3]){
                        dkstatus = 2;
                    }
                }
                appDaka.setStatus(dkstatus);

            }else{

                //判断状态
                Integer status = 0; //缺卡

                if(dakaConfigDto.getNum() == 2){
                    //如果当前时间没有超过当前下班点，则只能打卡到当前状态
                    if(dakaFlag == 1){
                        if(nowTime3[3]>config4[3]) {
                            status = 0;
                        }else if(nowTime3[3]>config1[3]){
                            status = 3; //迟到
                        }
                    }
                    if(dakaFlag == 4){
                        if(nowTime3[3]<config4[3]){
                            status = 3; //迟到
                        }
                    }
                }else{
                    //如果当前时间没有超过当前下班点，则只能打卡到当前状态
                    if(dakaFlag == 1){
                        if(nowTime3[3]>config4[3]) {
                            status = 0;
                        }else if(nowTime3[3]>config1[3]){
                            status = 3; //迟到
                        }
                    }
                    if(dakaFlag == 2){
                        if(nowTime3[3]<config2[3]){
                            status = 2; //早退
                        }
                    }
                    if(dakaFlag == 3){
                        if(nowTime3[3]>config4[3]) {
                            status = 0;
                        }else if(nowTime3[3]>config3[3]){
                            status = 3; //迟到
                        }
                    }
                    if(dakaFlag == 4){
                        if(nowTime3[3]<config4[3]){
                            status = 3; //迟到
                        }
                    }
                }

                appDaka.setStatus(status);   //缺卡
            }
            appDakaRepository.save(appDaka);

            //拦截，防止没过时间，1次打2回卡（目前逻辑是包含了自动补卡逻辑）--必须放下面，不然，提前下班走不了
            if(dakaConfigDto.getNum() == 2){
                //如果当前时间没有超过当前下班点，则只能打卡到当前状态
                if(dakaFlag == 1 && nowTime3[3]<config4[3]){
                    break;
                }
            }else{
                //如果当前时间没有超过当前下班点，则只能打卡到当前状态
                if(dakaFlag == 1 && nowTime3[3]<config2[3]){
                    break;
                }else {
                    if (dakaFlag == 3 && nowTime3[3] < config4[3]) {
                        break;
                    }
                }
            }

            if(dakaConfigDto.getNum() == 2){
                if(dakaFlag == 1){
                    dakaFlag = 3;   //只有2步（1，4）
                }
            }
        }

        return AjaxResult.success("打卡成功");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AppDakaDto create(AppDaka resources) {
        return appDakaMapper.toDto(appDakaRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(AppDaka resources) {
        AppDaka appDaka = appDakaRepository.findById(resources.getDkId()).orElseGet(AppDaka::new);
        ValidationUtil.isNull( appDaka.getDkId(),"AppDaka","id",resources.getDkId());
        appDaka.copy(resources);
        appDakaRepository.save(appDaka);
    }

    @Override
    public void deleteAll(Integer[] ids) {
        for (Integer dkId : ids) {
            appDakaRepository.deleteById(dkId);
        }
    }

    @Override
    public void download(List<AppDakaDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (AppDakaDto appDaka : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("责任区ID", appDaka.getAreaId());
            map.put("用户ID", appDaka.getUserId());
            map.put("上班卡或下班卡", appDaka.getTitle());
            map.put("规定打卡时间", appDaka.getStime());
            map.put("2或4个时间点", appDaka.getNum());
            map.put("打卡JSON", appDaka.getJson());
            map.put("状态  0缺卡，1正常，2早退，3迟到", appDaka.getStatus());
            map.put(" createTime",  appDaka.getCreateTime());
            map.put(" updateTime",  appDaka.getUpdateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}